package dt.inlee.system.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.alibaba.fastjson.JSON;
import com.opensymphony.xwork2.ActionSupport;

import dt.inlee.common.constant.CommonConstant;
import dt.inlee.common.exception.FrameworkException;
import dt.inlee.common.util.BaseUtil;
import dt.inlee.common.vo.PageBean;
import dt.inlee.domain.BusinessDictionary;
import dt.inlee.domain.BusinessDictionaryDetail;
import dt.inlee.system.service.BusinessDictionaryService;
import dt.inlee.system.vo.BusinessDictionaryBean;
import dt.inlee.system.vo.BusinessDictionaryDetailBean;

/**
 * @功能说明：业务字典和业务字典明细控制层
 * @作者：雷运梅、潘瑞峥
 * @创建日期：2010-6-5
 */
@Scope("prototype")
@Results( { @Result(name = "success", type = "json") })
@Controller("businessDictionaryAction")
public class BusinessDictionaryAction extends ActionSupport {

	private static final long serialVersionUID = -7085101001772580445L;
	@Autowired
	private BusinessDictionaryService businessDictionaryService;
	// 业务字典需要显示的结果
	private List<BusinessDictionaryBean> businessDictionaryBeans = new ArrayList<BusinessDictionaryBean>();
	// 业务字典明细需要显示的结果
	private List<BusinessDictionaryDetailBean> businessDictionaryDetailBeans = new ArrayList<BusinessDictionaryDetailBean>();
	// 业务字典VO
	private BusinessDictionaryBean businessDictionaryBean = new BusinessDictionaryBean();
	// 业务字典明细VO
	private BusinessDictionaryDetailBean businessDictionaryDetailBean = new BusinessDictionaryDetailBean();
	// 分页
	private PageBean pageBean = new PageBean();
	// ajax传来的新增、修改、删除的值
	private String values;
	// 返回给js处理的结果
	private boolean result = false;
	private JSONObject jsonObject;

	public JSONObject getJsonObject() {
		return jsonObject;
	}

	public void setJsonObject(JSONObject jsonObject) {
		this.jsonObject = jsonObject;
	}

	public BusinessDictionaryService getBusinessDictionaryService() {
		return businessDictionaryService;
	}

	public void setBusinessDictionaryService(BusinessDictionaryService businessDictionaryService) {
		this.businessDictionaryService = businessDictionaryService;
	}

	public List<BusinessDictionaryBean> getBusinessDictionaryBeans() {
		return businessDictionaryBeans;
	}

	public void setBusinessDictionaryBeans(List<BusinessDictionaryBean> businessDictionaryBeans) {
		this.businessDictionaryBeans = businessDictionaryBeans;
	}

	public List<BusinessDictionaryDetailBean> getBusinessDictionaryDetailBeans() {
		return businessDictionaryDetailBeans;
	}

	public void setBusinessDictionaryDetailBeans(List<BusinessDictionaryDetailBean> businessDictionaryDetailBeans) {
		this.businessDictionaryDetailBeans = businessDictionaryDetailBeans;
	}

	public BusinessDictionaryBean getBusinessDictionaryBean() {
		return businessDictionaryBean;
	}

	public void setBusinessDictionaryBean(BusinessDictionaryBean businessDictionaryBean) {
		this.businessDictionaryBean = businessDictionaryBean;
	}

	public BusinessDictionaryDetailBean getBusinessDictionaryDetailBean() {
		return businessDictionaryDetailBean;
	}

	public void setBusinessDictionaryDetailBean(BusinessDictionaryDetailBean businessDictionaryDetailBean) {
		this.businessDictionaryDetailBean = businessDictionaryDetailBean;
	}

	public PageBean getPageBean() {
		return pageBean;
	}

	public void setPageBean(PageBean pageBean) {
		this.pageBean = pageBean;
	}

	public String getValues() {
		return values;
	}

	public void setValues(String values) {
		this.values = values;
	}

	public boolean isResult() {
		return result;
	}

	public void setResult(boolean result) {
		this.result = result;
	}

	/**
	 * 查询业务字典参数信息
	 * 
	 * @return
	 * @throws FrameworkException, Exception
	 */
	@Action(value = "findAllBusinessDictionaries", results = { @Result(type = "json") })
	public String findAllBusinessDictionaries() throws FrameworkException, Exception {
		// jqGrid查询转码-utf-8
		BaseUtil.decodeObject(this.businessDictionaryBean);
		this.pageBean.init(this.businessDictionaryService.getBusinessDictionaryTotalRows(this.businessDictionaryBean
				.getCnName(), this.businessDictionaryBean.getEnName()));
		List<BusinessDictionary> businessDictionaries = this.businessDictionaryService.findAllBusinessDictionaries(
				this.businessDictionaryBean.getCnName(), this.businessDictionaryBean.getEnName(), this.pageBean
						.getCurPage(), this.pageBean.getPageSize());
		for (BusinessDictionary businessDictionary : businessDictionaries) {
			BusinessDictionaryBean bean = new BusinessDictionaryBean();
			BeanUtils.copyProperties(businessDictionary, bean);
			bean.setFlag(bean.getFlag().charValue() == CommonConstant.FLAG_VARIABLE ? '是' : '否');
			this.businessDictionaryBeans.add(bean);
		}
		return SUCCESS;
	}

	/**
	 * 通过业务字典参数ID删除业务字典参数信息
	 * 
	 * @return
	 * @throws FrameworkException
	 */
	@Action(value = "deleteBusinessDictionary", results = { @Result(name = "success", type = "chain", location = "findAllBusinessDictionaries") })
	@SkipValidation()
	public String deleteBusinessDictionary() throws FrameworkException {
		this.businessDictionaryService.deleteBusinessDictionaryById(this.businessDictionaryBean.getDeleteIDs());
		return SUCCESS;
	}

	/**
	 * 修改业务字典是时通过修改业务ID获取修改业务信息
	 * 
	 * @return
	 * @throws FrameworkException, Exception
	 */
	@Action(value = "findBusinessDictionary", results = { @Result(name = "success", location = "/page/system/business_dictionary_modify.jsp") })
	@SkipValidation()
	public String findBusinessDictionary() throws FrameworkException, Exception {
		BusinessDictionary businessDictionary = this.businessDictionaryService
				.findBusinessDictionaryById(this.businessDictionaryBean.getId());
		BeanUtils.copyProperties(businessDictionary, this.businessDictionaryBean);
		return SUCCESS;
	}

	/**
	 * 修改业务字典时通过字典id获取字典信息及明细
	 * 
	 * @return
	 * @throws FrameworkException, Exception
	 */
	@Action(value = "findBusinessDictionaryDetails", results = { @Result(type = "json") })
	@SkipValidation()
	public String findBusinessDictionaryDetails() throws FrameworkException, Exception {
		BusinessDictionary businessDictionary = this.businessDictionaryService
				.findBusinessDictionaryById(this.businessDictionaryBean.getId());
		BeanUtils.copyProperties(businessDictionary, this.businessDictionaryBean);
		List<BusinessDictionaryDetail> businessDictionaryDetails = businessDictionary.getBusinessDictionaryDetails();
		for (BusinessDictionaryDetail businessDictionaryDetail : businessDictionaryDetails) {
			BusinessDictionaryDetailBean bean = new BusinessDictionaryDetailBean();
			BeanUtils.copyProperties(businessDictionaryDetail, bean);
			this.getBusinessDictionaryDetailBeans().add(bean);
		}
		return SUCCESS;
	}

	/**
	 * 进入业务字典参数添加页面
	 * 
	 * @return
	 * @throws FrameworkException
	 */
	@Action(value = "createBusinessDictionary", results = { @Result(name = "success", location = "/page/system/business_dictionary_detail.jsp") })
	@SkipValidation()
	public String createBusinessDictionary() throws FrameworkException {
		return SUCCESS;
	}

	/**
	 * 修改业务字典及字典明细
	 * 
	 * @return
	 * @throws FrameworkException, Exception
	 */
	@Action(value = "modifyBusinessDictionary", results = { @Result(type = "json", params = { "excludeNullProperties",
			"true", "includeProperties", "result" }) })
	public String modifyBusinessDictionary() throws FrameworkException, Exception {
		// 需要传给service的参数，参数可为空
		String insertVal = null;
		String updateVal = null;
		String deleteVal = null;
		// 解码
		BaseUtil.decodeObject(this.getBusinessDictionaryBean());
		// 给业务字典赋新值
		BusinessDictionary businessDictionary = new BusinessDictionary();
		businessDictionary.setId(this.getBusinessDictionaryBean().getId());
		businessDictionary.setCnName(this.getBusinessDictionaryBean().getCnName());
		businessDictionary.setEnName(this.getBusinessDictionaryBean().getEnName());
		businessDictionary.setFlag(this.getBusinessDictionaryBean().getFlag());
		businessDictionary.setRemark(this.getBusinessDictionaryBean().getRemark());
		// 重名情况，js返回false
		if (!BaseUtil.isEmpty(businessDictionaryService.findBusinessDictionaryByIdAndName(this
				.getBusinessDictionaryBean().getId(), this.getBusinessDictionaryBean().getEnName(), this
				.getBusinessDictionaryBean().getCnName()))) {
			this.setResult(false);
			return SUCCESS;
		}
		// 拆分js传来的明细values参数，并自动赋给insertVal，updateVal，deleteVal
		if (null != this.getValues()) {
			String[] values = this.getValues().split("\\|\\|");
			int size = values.length;
			if (1 == size) {
				// 新增
				if (null != values[0] && !"".equals(values[0].trim())) {
					insertVal = values[0].trim();
				}
			} else if (2 == size) {
				// 新增和修改
				if (null != values[0] && !"".equals(values[0].trim())) {
					insertVal = values[0].trim();
				}
				if (null != values[1] && !"".equals(values[1].trim())) {
					updateVal = values[1].trim();
				}
			} else if (3 == size) {
				// 新增、修改、删除
				if (null != values[0] && !"".equals(values[0].trim())) {
					insertVal = values[0].trim();
				}
				if (null != values[1] && !"".equals(values[1].trim())) {
					updateVal = values[1].trim();
				}
				if (null != values[2] && !"".equals(values[2].trim())) {
					deleteVal = values[2].trim();
				}
			}
		}
		businessDictionaryService.updateBusinessDictionaryDetail(businessDictionary, insertVal, updateVal, deleteVal);
		this.setResult(true);
		return SUCCESS;
	}

	/**
	 * 新增业务字典及字典明细
	 * 
	 * @return
	 * @throws FrameworkException, Exception
	 */
	@Action(value = "saveBusinessDictionary", results = { @Result(type = "json", params = { "excludeNullProperties",
			"true", "includeProperties", "result" }) })
	public String saveBusinessDictionary() throws FrameworkException, Exception {
		// 解码
		BaseUtil.decodeObject(this.getBusinessDictionaryBean());
		// 判断重名，重名给js返回false
		if (!BaseUtil.isEmpty(businessDictionaryService.findBusinessDictionaryByName(this.getBusinessDictionaryBean()
				.getEnName(), this.getBusinessDictionaryBean().getCnName()))) {
			this.setResult(false);
			return SUCCESS;
		}
		// 为businessDictionary赋值
		BusinessDictionary businessDictionary = new BusinessDictionary();
		businessDictionary.setCnName(this.getBusinessDictionaryBean().getCnName());
		businessDictionary.setEnName(this.getBusinessDictionaryBean().getEnName());
		businessDictionary.setFlag(this.getBusinessDictionaryBean().getFlag());
		businessDictionary.setRemark(this.getBusinessDictionaryBean().getRemark());
		// 字典明细list
		List<BusinessDictionaryDetail> list = new ArrayList<BusinessDictionaryDetail>();
		for (String val : this.getValues().split(",")) {
			BusinessDictionaryDetail businessDictionaryDetail = new BusinessDictionaryDetail();
			businessDictionaryDetail.setName(val.split(";")[0]);
			businessDictionaryDetail.setValue(val.split(";")[1]);
			if (val.split(";").length < 3) {
				businessDictionaryDetail.setRemark("");
			} else {
				businessDictionaryDetail.setRemark(val.split(";")[2]);
			}
			list.add(businessDictionaryDetail);
		}
		businessDictionaryService.saveBusinessDictionary(businessDictionary, list);
		this.setResult(true);
		return SUCCESS;
	}

	/**
	 * 查询系统初始化参数列表forEasyui
	 * @return
	 * @throws FrameworkException
	 * @throws Exception
	 */
	@Action(value = "findAllBusWordbookEasyui", results = { @Result(type = "json", name = "success", params = {
			"root", "jsonObject" }) })
	@SkipValidation()
	public String findAllBusWordbookEasyui() throws FrameworkException, Exception {
		BaseUtil.decodeObject(this.businessDictionaryBean);
		// 行数
		int pageSize = Integer.parseInt((String) ServletActionContext
				.getRequest().getParameter("rows"));
		// 当前页码数
		int pageIndex = Integer.parseInt((String) ServletActionContext
				.getRequest().getParameter("page"));
		
		this.pageBean.init(this.businessDictionaryService.getBusinessDictionaryTotalRows(this.businessDictionaryBean
				.getCnName(), this.businessDictionaryBean.getEnName()));
		
		List<BusinessDictionary> businessDictionaries = this.businessDictionaryService
				.findAllBusinessDictionaries(this.businessDictionaryBean.getCnName(),
						this.businessDictionaryBean.getEnName(), pageIndex, pageSize);
		
		List<BusinessDictionaryBean> beanList = new ArrayList<BusinessDictionaryBean>();
		BusinessDictionaryBean bean = null;
		for (BusinessDictionary businessDictionary : businessDictionaries) {
			bean = new BusinessDictionaryBean();
			BeanUtils.copyProperties(businessDictionary, bean);
			bean.setFlag(bean.getFlag().charValue() == CommonConstant.FLAG_VARIABLE ? '是' : '否');
			beanList.add(bean);
		}
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("rows", beanList);
		jsonMap.put("total", pageBean.getTotalRecords());
		jsonObject = JSONObject.fromObject(jsonMap);
		return SUCCESS;
	}
	
	
	/**
	 * 新增业务字典及字典明细easyui
	 * 
	 * @return
	 * @throws FrameworkException, Exception
	 */
	@Action(value = "saveBusDictionary", results = { @Result(type = "json", name = "success", params = {
			"root", "jsonObject" }) })
	public String saveBusDictionary() throws FrameworkException, Exception {
		// 解码
		BaseUtil.decodeObject(this.getBusinessDictionaryBean());
		String context = "";
		boolean flag = true;
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		String dicId = this.getBusinessDictionaryBean().getId();
		// 给业务字典赋新值
		BusinessDictionary businessDictionary = null;
		
		//设置请求编码
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setCharacterEncoding("UTF-8");
		//获取编辑数据 这里获取到的是json字符串
		String deleted = request.getParameter("deleted");
		String inserted = request.getParameter("inserted");
		String updated = request.getParameter("updated");
		// 字典明细list
		List<BusinessDictionaryDetail> list = new ArrayList<BusinessDictionaryDetail>();
		//新增或者修改
		if(!BaseUtil.isEmpty(dicId)){
			if (!BaseUtil.isEmpty(businessDictionaryService.findBusinessDictionaryByIdAndName(dicId,this.getBusinessDictionaryBean()
					.getEnName(), this.getBusinessDictionaryBean().getCnName()))) {
				context = "已有该英文名称或中文名称!";
				flag = false;
			}else{
				businessDictionary = this.businessDictionaryService.findBusinessDictionaryById(this.getBusinessDictionaryBean().getId());
				businessDictionary.setCnName(this.getBusinessDictionaryBean().getCnName());
				businessDictionary.setEnName(this.getBusinessDictionaryBean().getEnName());
				businessDictionary.setFlag(this.getBusinessDictionaryBean().getFlag());
				businessDictionary.setRemark(this.getBusinessDictionaryBean().getRemark());
				//删除
				if(!BaseUtil.isEmpty(deleted)){
					List<BusinessDictionaryDetailBean> listDelete = JSON.parseArray(deleted, BusinessDictionaryDetailBean.class);
					this.businessDictionaryService.deleteBusDictionaryDetailByIds(businessDictionary,listDelete);
				}
				//插入
				if(!BaseUtil.isEmpty(inserted)){
					//把json字符串转换成对象
					List<BusinessDictionaryDetailBean> listInserted = JSON.parseArray(inserted, BusinessDictionaryDetailBean.class);
					this.businessDictionaryService.insertBusDictionaryDetailByIds(businessDictionary,listInserted);
				}
				//修改
				if(!BaseUtil.isEmpty(updated)){
					List<BusinessDictionaryDetailBean> listUpdated = JSON.parseArray(updated, BusinessDictionaryDetailBean.class);
					this.businessDictionaryService.updateBusDictionaryDetailByIds(businessDictionary,listUpdated);
				}
				this.businessDictionaryService.updateBusinessDictionary(businessDictionary);
			}
		}else{
			// 判断重名，重名给js返回false
			if (!BaseUtil.isEmpty(businessDictionaryService.findBusinessDictionaryByName(this.getBusinessDictionaryBean()
					.getEnName(), this.getBusinessDictionaryBean().getCnName()))) {
				context = "已有该英文名称或中文名称!";
				flag = false;
			}else{
				businessDictionary = new BusinessDictionary();
				businessDictionary.setCnName(this.getBusinessDictionaryBean().getCnName());
				businessDictionary.setEnName(this.getBusinessDictionaryBean().getEnName());
				businessDictionary.setFlag(this.getBusinessDictionaryBean().getFlag());
				businessDictionary.setRemark(this.getBusinessDictionaryBean().getRemark());
				//插入
				if(!BaseUtil.isEmpty(inserted)){
					//把json字符串转换成对象
					List<BusinessDictionaryDetailBean> listInserted = JSON.parseArray(inserted, BusinessDictionaryDetailBean.class);
					BusinessDictionaryDetail entity = null;
					for (BusinessDictionaryDetailBean bean : listInserted) {
						entity = new BusinessDictionaryDetail();
						entity.setName(bean.getName());
						entity.setRemark(bean.getRemark());
						entity.setValue(bean.getValue());
						list.add(entity);
					}					
				}
				businessDictionaryService.saveBusinessDictionary(businessDictionary, list);
			}
		}
		jsonMap.put("flag", flag);
		jsonMap.put("context",context);
		jsonObject = JSONObject.fromObject(jsonMap);
		return SUCCESS;
	}
	
	/**
	 * 通过业务字典参数ID删除业务字典参数信息easyui
	 * 
	 * @return
	 * @throws FrameworkException
	 */
	@Action(value = "deleteBusDictionary", results = { @Result(type = "json", name = "success", params = {
			"root", "jsonObject" }) })
	public String deleteBusDictionary() throws FrameworkException {
		boolean flag = true;
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		this.businessDictionaryService.deleteBusDictionaryByIds(this.businessDictionaryBean.getDeleteIDs());
		jsonMap.put("flag", flag);
		jsonObject = JSONObject.fromObject(jsonMap);
		return SUCCESS;
	}
	
	/**
	 * 修改业务字典是时通过修改业务ID获取修改业务信息easyui
	 * 
	 * @return
	 * @throws FrameworkException, Exception
	 */
	@Action(value = "findBusDictionary", results = { @Result(type = "json", name = "success", params = {
			"root", "jsonObject" }) })
	@SkipValidation()
	public String findBusDictionary() throws FrameworkException, Exception {
		BusinessDictionary businessDictionary = this.businessDictionaryService
				.findBusinessDictionaryById(this.businessDictionaryBean.getId());
		BeanUtils.copyProperties(businessDictionary,
				this.businessDictionaryBean);
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("bean", businessDictionaryBean);
		jsonObject = JSONObject.fromObject(jsonMap);
		return SUCCESS;
	}
	
	/**
	 * 修改业务字典时通过字典id获取字典信息及明细
	 * 
	 * @return
	 * @throws FrameworkException, Exception
	 */
	@Action(value = "findBusDictionaryDetails", results = { @Result(type = "json", name = "success", params = {
			"root", "jsonObject" }) })
	@SkipValidation()
	public String findBusDictionaryDetails() throws FrameworkException, Exception {
		BusinessDictionary businessDictionary = this.businessDictionaryService
				.findBusinessDictionaryById(this.businessDictionaryBean.getId());
		BeanUtils.copyProperties(businessDictionary, this.businessDictionaryBean);
		List<BusinessDictionaryDetail> businessDictionaryDetails = businessDictionary.getBusinessDictionaryDetails();
		for (BusinessDictionaryDetail businessDictionaryDetail : businessDictionaryDetails) {
			BusinessDictionaryDetailBean bean = new BusinessDictionaryDetailBean();
			BeanUtils.copyProperties(businessDictionaryDetail, bean);
			this.getBusinessDictionaryDetailBeans().add(bean);
		}
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("rows", this.getBusinessDictionaryDetailBeans());
		jsonObject = JSONObject.fromObject(jsonMap);
		return SUCCESS;
	}
}